package com.imflea.zero.service.meeting.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imflea.zero.model.dao.meeting.MeetingRoomMapper;
import com.imflea.zero.model.entity.meeting.MeetingRoom;
import com.imflea.zero.model.entity.meeting.MeetingShop;
import com.imflea.zero.model.entity.meeting.dto.MeetingRoomDto;
import com.imflea.zero.model.entity.meeting.dto.RoomStatProvinceDto;
import com.imflea.zero.model.entity.meeting.vo.MeetingAreaStatVo;
import com.imflea.zero.model.entity.meeting.vo.MeetingRoomDetailVO;
import com.imflea.zero.model.entity.qx.BaseArea;
import com.imflea.zero.model.entity.qx.BaseDict;
import com.imflea.zero.service.meeting.IMeetingRoomService;
import com.imflea.zero.service.meeting.IMeetingShopService;
import com.imflea.zero.service.qx.IBaseAreaService;
import com.imflea.zero.service.qx.IBaseDictService;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.utils.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 空间表 服务实现类
 * </p>
 *
 * @author xby
 * @since 2024-01-25
 */
@Service
public class MeetingRoomServiceImpl extends ServiceImpl<MeetingRoomMapper, MeetingRoom> implements IMeetingRoomService {
    @Autowired
    private IMeetingShopService iMeetingShopService;
    @Autowired
    private IBaseDictService baseDictService;
    @Autowired
    private IBaseAreaService baseAreaService;

    @Override
    public MeetingRoom saveOrUpdateMeetingRoom(MeetingRoom entity) {
        if (CommonUtils.isNull(entity.getId())) {
            entity.setId(CommonUtils.generateRandomString());
            entity.setStatus("0");

        }
        if (CommonUtils.isNull(entity.getLongRent())) {
            entity.setLongRent("0");
        }
        entity.setTenantId(SessionUtils.getTenantId());
        this.saveOrUpdate(entity);
        return entity;
    }

    @Override
    public PageInfo<MeetingRoomDetailVO> queryPage(MeetingRoomDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        String province = dto.getProvince();
        String city = dto.getCity();
        String region = dto.getRegion();
        String status = dto.getStatus();
        List<BaseArea> areas = baseAreaService.list();

        QueryWrapper<MeetingRoom> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        if (!CommonUtils.isNull(status)) {
            queryWrapper.eq("status", status);
        }
        if (!CommonUtils.isNull(dto.getShopId())) {
            queryWrapper.eq("shop_id", dto.getShopId());
        }
        if (!CommonUtils.isNull(dto.getRoomCategory())) {
            queryWrapper.eq("room_category", dto.getRoomCategory());
        }
        List<MeetingShop> listShops = iMeetingShopService.listAll(province, city, region);

        Map<String, MeetingShop> shops = listShops.stream().collect(Collectors.toMap(MeetingShop::getId, (p) -> p));
        Set<String> shopIds = shops.keySet();
        if (CommonUtils.isNull(shopIds)) {
            PageInfo<MeetingRoomDetailVO> pageResultDetail = new PageInfo<>(Collections.emptyList());
            pageResultDetail.setTotal(0);
            return pageResultDetail;
        } else {
            queryWrapper.in("shop_id", shopIds);
        }

        queryWrapper.eq("room_type", dto.getRoomType());
        PageHelper.startPage(pageIndex, pageSize);
        List<MeetingRoom> adoptInfos = this.list(queryWrapper);
        PageInfo<MeetingRoom> pageResult = new PageInfo<>(adoptInfos);
        List<MeetingRoomDetailVO> detailVOS = new ArrayList<>();


        for (MeetingRoom room : adoptInfos) {
            MeetingRoomDetailVO vo = new MeetingRoomDetailVO();
            BeanUtil.copyProperties(room, vo);
            MeetingShop meetingShop = shops.get(room.getShopId());

            String provinceId = meetingShop.getProvince();
            String cityId = meetingShop.getCity();
            String regionId = meetingShop.getRegion();
            List<BaseArea> provinces = areas.stream().filter(item -> item.getId().equals(provinceId)).collect(Collectors.toList());
            if (!CommonUtils.isNull(provinces)) {
                String areaName = provinces.get(0).getAreaName();
                vo.setProvinceName(areaName);
            }
            List<BaseArea> cities = areas.stream().filter(item -> item.getId().equals(cityId)).collect(Collectors.toList());
            if (!CommonUtils.isNull(cities)) {
                String areaName = cities.get(0).getAreaName();
                vo.setCityName(areaName);
            }
            List<BaseArea> regions = areas.stream().filter(item -> item.getId().equals(regionId)).collect(Collectors.toList());
            if (!CommonUtils.isNull(regions)) {
                String areaName = regions.get(0).getAreaName();
                vo.setRegionName(areaName);
            }
            vo.setShopName(meetingShop.getCompanyName());

            detailVOS.add(vo);
        }


        PageInfo<MeetingRoomDetailVO> pageResultDetail = new PageInfo<>(detailVOS);
        pageResultDetail.setTotal(pageResult.getTotal());
        return pageResultDetail;
    }

    @Override
    public MeetingRoomDetailVO getDetailById(String id) {
        List<BaseDict> allRoomConfigDict = new ArrayList<>();
        MeetingRoomDetailVO vo = new MeetingRoomDetailVO();
        MeetingRoom entity = this.getById(id);
        if (!CommonUtils.isNull(entity)) {
            String configTags = entity.getConfigTag();
            if (!CommonUtils.isNull(configTags)) {
                List<String> configs = Arrays.asList(configTags.split(","));
//                XBGKJ
//                HYS_BQ
                List<BaseDict> ltRoom = baseDictService.queryByPcode("XBGKJ");//小型会议室
                List<BaseDict> gtRoom = baseDictService.queryByPcode("HYS_BQ");//多功能空间
                allRoomConfigDict.addAll(ltRoom);
                allRoomConfigDict.addAll(gtRoom);
                StringBuffer bf = new StringBuffer("");
                for (String config : configs) {
                    for (BaseDict tag : allRoomConfigDict) {
                        if (tag.getId().equals(config)) {
                            bf.append(tag.getDictName());
                            bf.append(",");
                            break;
                        }
                    }
                }
                String confName = bf.toString();
                if (confName.length() > 0) {
                    confName = confName.substring(0, confName.length() - 1);
                }

                BeanUtil.copyProperties(entity, vo);
                vo.setConfigTagName(confName);
            }
        }

        return vo;
    }

    @Override
    public List<MeetingAreaStatVo> statRoomProvinceByRoomType(RoomStatProvinceDto meetingRoomDto) {
        String roomType = meetingRoomDto.getRoomType();
        String tenantId = SessionUtils.getTenantId();
        List<BaseArea> baseProvinces = baseAreaService.queryByParendId(null);

        Map<BaseArea, Integer> result = new HashMap<>();
        List<MeetingAreaStatVo> vos = new ArrayList<>();

        QueryWrapper<MeetingShop> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
//
//        if (!CommonUtils.isNull(roomType)) {
//            queryWrapper.eq("room_type", roomType);
//        }
        List<MeetingShop> list = iMeetingShopService.list(queryWrapper);
        Map<String, List<MeetingShop>> groups = list.stream().collect(Collectors.groupingBy(MeetingShop::getProvince));
        Set<String> provinces = groups.keySet();

        for (String province : provinces) {
            List<MeetingShop> everyProvinceShop = groups.get(province);
            List<String> shopIds = everyProvinceShop.stream().map(item -> item.getId()).collect(Collectors.toList());
            List<MeetingRoom> meetingRooms = this.queryByShopIdsAndRoomType(shopIds, roomType);
            List<BaseArea> collect = baseProvinces.stream().filter((BaseArea area) -> area.getId().equals(province)).collect(Collectors.toList());
            if (!CommonUtils.isNull(collect)) {
                Integer count = 0;
                if (!CommonUtils.isNull(meetingRooms)) {
                    count = meetingRooms.size();
                    MeetingAreaStatVo vo = new MeetingAreaStatVo();
                    BeanUtil.copyProperties(collect.get(0), vo);
                    vo.setCount(count);
                    vos.add(vo);
                }

            }


        }
        return vos;
    }

    @Override
    public List<MeetingRoom> queryByShopIds(List<String> shopIds) {
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<MeetingRoom> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        queryWrapper.in("shop_id", shopIds);
        return this.list(queryWrapper);
    }

    @Override
    public List<MeetingRoom> queryByShopId(String shopId) {
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<MeetingRoom> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        queryWrapper.eq("shop_id", shopId);
        return this.list(queryWrapper);
    }

    @Override
    public List<MeetingRoom> queryByShopIdsAndRoomType(List<String> shopIds, String roomType) {
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<MeetingRoom> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        queryWrapper.eq("room_type", roomType);
        queryWrapper.in("shop_id", shopIds);

        return this.list(queryWrapper);
    }

    @Override
    public Boolean updateStatusById(String id, String status) {
        UpdateWrapper<MeetingRoom> queryWrapper = new UpdateWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.set("status", status);
        boolean update = this.update(queryWrapper);
        return update;
    }

}
